<template>
  <div class="home">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="danger" @click="openDialog">新增</el-button>
    </div>
    <!--    搜素区域-->
    <div style="margin: 10px 0">
      <!--@change事件可以获取当前改变的对象-->
      <el-select v-model="value" placeholder="Select" @change="optionClick($event)">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"

        >
        </el-option>
      </el-select>
      <!--      清空按钮 clearable-->
      <el-input v-model="search" placeholder="请输入关键字" style="width: 20%" clearable/>
      <el-button type="primary" style="margin-left: 5px" @click="load">查询</el-button>
    </div>
    <!--    stripe斑马纹 sortable排序-->
    <!--    创建表格-->
    <el-table :data="tableData" border stripe style="width: 100%; " :header-cell-style="{textAlign: 'center'}"
              :cell-style="{textAlign: 'center'}">
      <el-table-column prop="seaExhibitId" label="动物Id" sortable/>
      <el-table-column prop="seaExhibitName" label="动物名称"/>
      <el-table-column prop="seaExhibitDynasty" label="动物级别"/>
      <el-table-column prop="seaExhibitDetail" label="动物介绍">
        <template #default="scope">
          <!--          设置本行的introduce用html语法展示-->
          <div v-html="scope.row.seaExhibitDetail"></div>
        </template>
      </el-table-column>
      <el-table-column prop="seaShowId" label="所属展厅id"/>
      <el-table-column label="动物图片">
        <!--        上传图片-->
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.cover"
              :preview-src-list="[scope.row.cover]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180" header-align="center">
        <template #default="scope">
          <!--        插槽名.row可以获取一行的内容，-->
          <!--        如果要获取行的索引，使用插槽名.$index，注意$符号是必不可少的，否则将不起作用。-->
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>

          <!--          <el-popconfirm title="确定要删除吗">弹窗提示框确定要删除吗-->
          <!--          @confirm事件单击确认按钮时触发-->
          <el-popconfirm title="确定要删除吗" @confirm="handleDelete(scope.row.seaExhibitId)">
            <template #reference>
              <el-button type="text" size="small">Delete</el-button>
            </template>
          </el-popconfirm>
        </template>

      </el-table-column>
    </el-table>

    <!--    创建分页-->
    <div style="margin: 10px 0">
      <el-pagination
          v-model:currentPage="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <!--    弹窗功能，弹窗里面创建表单-->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">

      <!--      创建表单 弹窗里面的表单-->
      <el-form :model="form" label-width="120px">
        <el-form-item label="展品名">
          <el-input v-model="form.seaExhibitName" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="所属朝代">
          <el-input v-model="form.seaExhibitDynasty" style="width: 80%"></el-input>
        </el-form-item>
        <div id="div1"></div>
        <el-form-item label="所属展厅">
          <el-input v-model="form.seaShowId" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <!--          :on-success表示具体选择了哪张图片-->
          <el-upload ref="upload"
                     action="http://localhost:8090/file/upload" :on-success="fileUploadSuccess">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">提交</el-button>
      </span>
      </template>
    </el-dialog>
  </div>

</template>

<script>
import {ref} from "vue";
import request from "@/utils/request";
import E from "wangeditor";
let editor; //富文本编辑器 去wangEditor官网查看
export default {
  name: "Exhibit",
  data() {
    return {
      search: '',
      currentPage: 1,
      pageSize: 3,
      total: 0,
      option: '',
      title:'',
      //设置弹窗为false，不显示
      dialogVisible: false,
      options: ref([
        {
          value: 'sea_exhibit_id',
          label: 'sea_exhibitId',
        },
        {
          value: 'sea_exhibit_name',
          label: 'exhibitName',

        },

      ]),
      value: ref(''),
      form: {},
      tableData: [
        {},

      ],

    }
  },
  created() {
    this.load()
  },
  methods: {
    //将后台查询的结果放到前台显示
    load() {
      request.get("/api/exhibit", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search,
          option: this.option

        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    // 操作下的编辑按钮 修改数据
    handleEdit(row) {
      this.title = '修改展品信息'
      console.log(row);
      // JSON.stringify()【从一个对象中解析出字符串】
      //JSON.parse()【从一个字符串中解析出json对象】
      //因为传入的row是一行对象，所以先将row解析成字符串，再将字符串解析成JSON对象
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true

      //解决未来dom不存在的问题,记得去百度一下

      this.$nextTick(()=>{//解决了初始化节点已存在编辑器实例，无法重复创建编辑器问题，如果为空 创建editor实例，不为空先销毁在重新创建一个新实例
        this.$refs['upload'].clearFiles() //清除历史文件
        if(editor==null){
          editor = new E('#div1')//富文本编辑器 关联弹窗里面的div new一个editor对象
          editor.config.uploadImgServer = 'http://localhost:8090/file/editor/upload'
          editor.config.uploadFileName = 'file'//设置上传参数名称
          editor.create()
          editor.txt.html(row.seaExhibitDetail)//设置富文本编辑器文本的内容为本行的content，以html展示
        }else {
          editor.destroy()
          editor = new E('#div1')//富文本编辑器 关联弹窗里面的div new一个editor对象
          editor.config.uploadImgServer = 'http://localhost:8090/file/editor/upload'
          editor.config.uploadFileName = 'file'//设置上传参数名称
          editor.create()
          editor.txt.html(row.seaExhibitDetail)//设置富文本编辑器文本的内容为本行的content，以html展示
        }

      })

    },

    // 删除表格中的某一行
    handleDelete(id) {

      request.delete('/api/exhibit/' + id).then(res => {
        console.log(res);
        if (res.code == '0') {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.dialogVisible = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
        this.load()
      })

    },

    // 改变每页的个数 ,element-plus提供了改变之后pageSize的值
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()

    },
    //改变当前页 element-plus提供了改变之后pageSize的值
    handleCurrentChange(pageNum) {

      this.currentPage = pageNum
      this.load()

    },

    //打开弹窗
    openDialog() {
      this.title = '新增展品'
      this.dialogVisible = true
      this.form = {}

      this.$nextTick(()=>{
        this.$refs['upload'].clearFiles() //清除历史文件
        if(editor==null){
          editor = new E('#div1')//富文本编辑器 关联弹窗里面的div new一个editor对象
          editor.txt.html("")
          editor.config.uploadImgServer = 'http://localhost:8090/file/editor/upload'
          editor.config.uploadFileName = 'file'//设置上传参数名称
          editor.create()
        }else{
          editor.destroy()
          editor = new E('#div1')//富文本编辑器 关联弹窗里面的div new一个editor对象
          editor.txt.html("")
          editor.config.uploadImgServer = 'http://localhost:8090/file/editor/upload'
          editor.config.uploadFileName = 'file'//设置上传参数名称
          editor.create()
        }

      })
    },
    //插入数据
    save() {
      this.form.seaExhibitDetail = editor.txt.html()//编辑器里面的值赋值到content实体中
      //如果表单里有id说明是更新操作，没有说明是插入操作
      if (this.form.seaExhibitId) {
        request.put('/api/exhibit', this.form).then(res => {
          console.log(res);
          if (res.code == '0') {
            this.$message({
              type: 'success',
              message: '更新成功'
            })
            this.dialogVisible = false
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
          this.load()
        })
        //重新刷新表格中的数据

      } else {
        request.post("/api/exhibit", this.form).then(res => {
          console.log(res);
          if (res.code == '0') {
            this.$message({
              type: 'success',
              message: '插入成功'
            })
            this.dialogVisible = false
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
          this.load()
        })

      }


    },
    optionClick(id) {
      this.option = id

    }
    ,
    fileUploadSuccess(response) {
      console.log(response);
      //将选中的文件路径传入到后端数据库中
      this.form.cover = response.data

    },

  },
  components: {},
}
</script>

<style scoped>

</style>